<template>
  <el-container v-loading="loading" :element-loading-text="loadingText">
    <!-- 侧边栏 -->
    <el-aside width="250px">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="下载列表" name="1">
          <div v-for="it in downlaodList" :key="it.index">
            <el-tag :closable="true" @close="removeDownloadFile(it)">{{
              it.showName
            }}</el-tag>
            <i
              :class="getIconClass(it)"
              v-if="it.status !== status.defalut"
            ></i>
          </div>
        </el-collapse-item>
        <el-collapse-item title="上传列表" name="2">
          <div v-for="(it, i) in uploadList" :key="i">
            <el-tag :closable="true" @close="removeUploadFile(it)">{{
              it.showName
            }}</el-tag>
            <i
              :class="getIconClass(it)"
              v-if="it.status !== status.defalut"
            ></i>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-aside>
    <!-- 内容区 -->
    <el-main>
      <div class="home_container">
        <!-- 头部导航 -->
        <div class="top_container">
          <div>
            <div
              class="top_nav"
              v-for="(it, index) in paths"
              :key="index"
              @click="goFolder(index)"
            >
              <div>
                <span
                  >{{ it }}
                  <i class="el-icon-arrow-right"></i>
                </span>
              </div>
            </div>
          </div>

          <div v-if="!isBatchDownload">
            <!-- 上传 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              circle
              @click.stop="uploadFile(curPath)"
            ></el-button>
            <!-- 下载 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              circle
              @click.stop="prepareBatchDownload"
            ></el-button>
          </div>
          <div v-else>
            <el-button
              type="info"
              icon="el-icon-close"
              circle
              size="mini"
              @click.stop="cancelDownload"
            ></el-button>
            <el-button
              type="success"
              icon="el-icon-check"
              circle
              size="mini"
              @click.stop="batchDownloadFiles"
            ></el-button>
          </div>
        </div>

        <!-- 文件列表 -->
        <div class="file_container" v-if="fileInfoList.length != 0">
          <el-checkbox-group v-model="checkList" @change="checkboxChange">
            <el-popover
              placement="bottom"
              trigger="manual"
              v-model="it._edit"
              v-for="it in fileInfoList"
              :key="it.id"
            >
              <div>
                <!-- 上传 -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-upload2"
                  circle
                  @click.stop="uploadFile(curPath + '/' + it.name)"
                ></el-button>
                <!-- 下载 -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-download"
                  circle
                  @click.stop="downloadSingleFile(it)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  circle
                  @click.stop="deleteFile(it)"
                ></el-button>
                <!-- 关闭 -->
                <el-button
                  size="mini"
                  icon="el-icon-close"
                  @click.stop="it._edit = false"
                  circle
                ></el-button>
              </div>

              <div
                slot="reference"
                class="touch_container"
                style="display: inline-block"
              >
                <v-touch
                  @press="it._edit = true"
                  @tap="openFloder(it)"
                  tag="span"
                >
                  <el-tag :class="it.is_dir ? 'cur-pointer' : ''" type="info">
                    <i v-if="it.is_dir" class="el-icon-folder"></i>
                    <i v-else class="el-icon-document"></i>
                    {{ it.name }}
                  </el-tag>
                </v-touch>
                <el-checkbox
                  :label="it.name"
                  v-show="it._cb_show"
                ></el-checkbox>
              </div>
            </el-popover>
          </el-checkbox-group>
        </div>
        <el-empty v-else description="暂无数据"></el-empty>
      </div>
    </el-main>
  </el-container>
</template>

<script>
let _ = require("lodash");
export default {
  name: "Home",
  data() {
    return {
      fileInfoList: [],
      curPath: "/sdcard",
      activeName: "1",
      paths: [],
      checkList: [],
      //下载文件列表
      downlaodList: [],
      //上传文件列表
      uploadList: [
        // { showName: "1", status: 0 },
        // { showName: "2", status: 2 },
        // { showName: "3", status: 3 },
        // { showName: "4", status: 4 },
      ],
      isBatchDownload: false,
      loading: false,
      //加载显示的问题
      loadingText: "",
      //文件下载的状态
      status: {
        //默认，还没有开始
        defalut: 0,
        //下载中
        download: 1,
        //上传中
        upload: 2,
        //成功的
        success: 3,
        //失败的
        failed: 4,
      },
    };
  },
  methods: {
    async getAllFiles(path) {
      const { data: res } = await this.$http.get("get_dir", {
        params: { path: path },
      });
      console.log(res);
      if (res.code != 200) {
        this.$message.error(`获取文件列表失败,${res.message}`);
        return;
      }
      res.data.sub_files.forEach((el, i) => {
        el._edit = false;
        el._cb_show = this.isBatchDownload === true;
        el.index = i;
      });
      this.fileInfoList = res.data.sub_files;
      this.curPath = res.data.cur_path;
    },
    //点击顶部导航栏打开对应的文件夹
    goFolder(index) {
      console.log("goFolder");
      const n = this.paths.length - index - 1;
      this.paths = _.dropRight(this.paths, n);
      this.getAllFiles("/" + this.paths.join("/"));
    },
    //打开文件夹
    openFloder(info) {
      console.log("openFloder");
      if (!info.is_dir) return;
      const toPath = this.curPath + "/" + info.name;
      this.paths.push(info.name);
      this.getAllFiles(toPath);
    },
    checkboxChange() {
      this.checkList.forEach((el) => {
        var showName = el.length > 12 ? el.slice(0, 13) : el;
        this.downlaodList.push({
          name: el,
          showName: showName,
          path: this.curPath + "/" + el,
          status: this.status.defalut,
        });
      });
      console.log(this.downlaodList);
    },
    //准备进行批量下载
    prepareBatchDownload() {
      this.isBatchDownload = true;
      this.fileInfoList.forEach((el) => {
        el._cb_show = true;
      });
    },
    //移除要下载的文件
    removeDownloadFile(it) {
      if (it.status === this.status.download) {
        this.$message.warning("下载中，不可移除");
        return;
      }
      this.downlaodList.remove(it);
      this.checkList.remove(it.name);
    },
    //取消下载
    cancelDownload() {
      this.isBatchDownload = false;
      this.checkList = [];
      this.downlaodList = [];
      this.fileInfoList.forEach((el) => {
        el._cb_show = false;
      });
    },
    //批量下载文件
    async batchDownloadFiles() {
      if (this.downlaodList.length === 0) {
        this.$message.warning("请选择要下载的文件");
        return;
      }
      this.isBatchDownload = false;
      this.fileInfoList.forEach((el) => {
        el._cb_show = false;
      });
      const { data: res } = await this.$http.get("choose_save_dir");
      if (res.code != 200) {
        this.$message.error("没有获取到要存放的文件目录");
        return;
      }
      for (var i = 0; i < this.downlaodList.length; i++) {
        const it = this.downlaodList[i];
        it.status = this.status.download;
        const { data: res2 } = await this.$http.post("download_file", {
          src_path: it.path,
          dst_path: res.data.dir_path,
        });
        it.status = res2.code == 200 ? this.status.success : this.status.error;
      }
    },
    //下载单个文件
    async downloadSingleFile(it) {
      it._edit = false;
      const { data: res } = await this.$http.get("choose_save_dir");
      if (res.code != 200) {
        this.$message.error("没有获取到要存放的文件目录");
        return;
      }
      if (res.data.dir_path.length === 0) return;
      this.loading = true;
      this.loadingText = `下载 ${it.name} 中。。。`;
      const { data: res2 } = await this.$http.post("download_file", {
        src_path: this.curPath + "/" + it.name,
        dst_path: res.data.dir_path,
      });

      if (res2.code !== 200) {
        this.$message.error("下载文件失败");
      } else {
        this.$message.success("下载成功");
      }
      this.loading = false;
      this.loadingText = "";
    },
    getIconClass(it) {
      if (it.status === this.status.defalut) {
        return "";
      } else if (it.status === this.status.download) {
        return "el-icon-loading";
      } else if (it.status === this.status.upload) {
        return "el-icon-loading";
      } else if (it.status === this.status.success) {
        return "el-icon-success";
      } else {
        return "el-icon-error";
      }
    },
    // 上传文件
    async uploadFile(dst_path) {
      const { data: res } = await this.$http.get("choose_upload_files");
      console.log(res);
      if (res.code != 200) {
        this.$message.error("没有选择要上传的文件");
        return;
      }

      if (res.data.length === 0) return;
      res.data.forEach((el) => {
        const fileName = el.file_name;
        const showName =
          fileName.length > 12 ? fileName.slice(0, 13) : fileName;
        this.uploadList.push({
          name: fileName,
          showName: showName,
          path: el.file_path,
          status: this.status.defalut,
        });
      });
      for (var i = 0; i < this.uploadList.length; i++) {
        const fileInfo = this.uploadList[i];
        console.log({ src_path: fileInfo.path, dst_dir: dst_path + "/" });
        fileInfo.status = this.status.upload;
        const { data: res2 } = await this.$http.put("upload_file", {
          src_path: fileInfo.path,
          dst_dir: dst_path + "/",
        });

        fileInfo.status =
          res2.code == 200 ? this.status.success : this.status.error;
      }

      this.$message.success("上传完成");
      this.getAllFiles(this.curPath);
    },
    //移除要上传的文件
    removeUploadFile(it) {
      if (it.status === this.status.download) {
        this.$message.warning("上传中，不可移除");
        return;
      }
      this.uploadList.remove(it);
    },
    //删除文件
    deleteFile(it) {
      this.$confirm(
        `确认要删除${it.is_dir ? "文件夹" : "文件"} ${it.name} 吗?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          it._edit = false;
          const { data: res } = await this.$http.delete("delete_file", {
            params: {
              path: this.curPath + "/" + it.name,
            },
          });
          if (res.code !== 200) {
            return this.$message.success("删除失败!");
          }
          this.getAllFiles(this.curPath + "/");
          this.$message.success("删除成功!");
        })
        .catch((error) => error);
    },
  },
  created() {
    this.paths.push("sdcard");
    this.getAllFiles("/sdcard");
  },
};
</script>

<style lang="less" scoped>
.el-container {
  height: 100%;
}
.el-aside {
  padding: 20px;
  height: 100%;
  border-right: 1px solid #ddd;
  .el-button {
    width: 100%;
  }
  div {
    margin-top: 10px;
    align-items: center;
    .el-tag {
      width: 180px;
      text-align: center;
      overflow: hidden;
      margin-bottom: 5px;
    }
    i {
      margin-left: 10px;
      position: relative;
      bottom: 16px;
    }
    i.el-icon-loading {
      color: rgb(83, 168, 255);
    }
    i.el-icon-error {
      color: red;
    }
    i.el-icon-success {
      color: #67c23a;
    }
  }

  // div {
  //   margin-top: 10px;
  //   display: flex;
  //   align-items: center;
  //   .el-tag {
  //     width: 120px;
  //     text-align: center;
  //     overflow: hidden;
  //   }
  //   i {
  //     margin-left: 10px;
  //   }
  //   i.el-icon-loading {
  //     color: rgb(83, 168, 255);
  //   }
  //   i.el-icon-error {
  //     color: red;
  //   }
  //   i.el-icon-success {
  //     color: #67c23a;
  //   }
  // }
}

.home_container {
  height: 100%;
  .top_nav {
    cursor: pointer;
  }
  .top_container {
    display: flex;
    justify-content: space-between;
    padding-right: 20px;
  }
}
.el-button {
  margin-bottom: 15px;
}
.file_container {
  margin-top: 15px;
  .el-tag {
    padding: 0 20px;
    margin-right: 15px;
    i {
      font-size: 15px;
    }
  }
}

.cur-pointer {
  cursor: pointer;
}

.el-breadcrumb__item {
  cursor: pointer !important;
}
.top_nav {
  display: inline-block;
}

.el-checkbox__label {
  display: none !important;
}

.touch_container {
  position: relative;
  margin-bottom: 20px;
  .el-checkbox {
    position: absolute;
    // transform: translate(-500%, 200%);
    left: -5px;
    top: -10px;
    // bottom: -10px;
    /deep/ .el-checkbox__label {
      display: none !important;
    }
  }
}
</style>